package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.ExceptionAll.MyCustomException;
import com.itheima.commit.R;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.service.CategoryService;
import com.itheima.service.DishService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    @Override
    public R<String> add(Category category) {
        this.save(category);
        return R.success("添加成功");
    }

    @Override
    public R<Page> selectAll(Integer page, Integer pageSize) {
        Page<Category> p = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSort);

        this.page(p, wrapper);

        return R.success(p);
    }

    @Override
    public R<String> delete(Long id) {

        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, id);
        int count = dishService.count(wrapper);
        if (count > 0) {
            throw new MyCustomException("该分类下有菜品，不能删除");
        }

        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Setmeal::getCategoryId, id);
        int count1 = setmealService.count(wrapper1);
        if (count1 > 0) {
            throw new MyCustomException("该套餐下有分类，不能删除");
        }

        this.removeById(id);
        return R.success("删除成功");
    }

    @Override
    public R<String> update(Category category) {
        this.updateById(category);
        return R.success("修改成功");
    }

    @Override
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(category.getType() != null, Category::getType, category.getType());
        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = list(wrapper);
        return R.success(list);
    }


}
